from .serializers import *
from apps.system.lessee.dao import LesseeDao
from apps.pay.order.dao import OrderDao
# from apps.pay.walletRecord.dao import WalletRecordDao
from apps.pay.financeForLessee.dao import FinanceForLesseeDao
from apps.pay.recordIncomes.dao import RecordIncomesDao
from apps.system.user.dao import UserDao
from apps.merchant.shop.dao import ShopDao

from django.db.models import Sum
from decimal import Decimal
import datetime
from django.db.models import Q
import json
from apps.common.utils.tools import random_num
from apps.common.utils.time import getFormatTime

def financeFun(dateCycle, date):

    lessees = LesseeDao().findAll()
    for lessee in lessees:
        data = {}
        data['lessee'] = lessee.id
        data['dateCycle'] = dateCycle
        _itemOrder = OrderDao().findAllMainOrder().filter(Q(orderStatus='WAIT_SEND') | Q(orderStatus='READY_SEND') | Q(orderStatus='WAIT_RECEIVE') | Q(orderStatus='FINISH'))
        _recordIncomes = RecordIncomesDao().findAll()
        _users = UserDao().findAllUser()

        # 管理员总充值
        addIncomeFromAdminAll = _recordIncomes.filter(payway='incomes', scene='addIncomeFromAdmin').aggregate(sums=Sum('money'))['sums'] or 0
        data['addIncomeFromAdminAll'] = Decimal(addIncomeFromAdminAll)
        # 管理员总扣除
        subIncomeFromAdminAll = _recordIncomes.filter(payway='incomes', scene='subIncomeFromAdmin').aggregate(sums=Sum('money'))['sums'] or 0
        data['subIncomeFromAdminAll'] = Decimal(subIncomeFromAdminAll)
        # 管理员总充值原积分
        addIncomesOriginalFromAdminAll = _recordIncomes.filter(payway='incomesOriginal', scene='addIncomeFromAdmin').aggregate(sums=Sum('money'))['sums'] or 0
        data['addIncomesOriginalFromAdminAll'] = Decimal(addIncomesOriginalFromAdminAll)
        # 管理员总扣除原积分
        subIncomesOriginalFromAdminAll = _recordIncomes.filter(payway='incomesOriginal', scene='subIncomeFromAdmin').aggregate(sums=Sum('money'))['sums'] or 0
        data['subIncomesOriginalFromAdminAll'] = Decimal(subIncomesOriginalFromAdminAll)
        # 微信支付总金额
        realPayALl = _itemOrder.filter(payway='wxpay').aggregate(sums=Sum('realPay'))['sums'] or 0
        data['realPayForWxPayAll'] = Decimal(realPayALl)
        # 积分支付总金额
        realPayForIncomesAll = _itemOrder.filter(payway='incomes').aggregate(sums=Sum('realPay'))['sums'] or 0
        data['realPayForIncomesAll'] = Decimal(realPayForIncomesAll)

        # 商户订单总金额
        shopOrderMoneyAll = _itemOrder.filter(scene='payForFranchisee').aggregate(sums=Sum('sellingPrice'))['sums'] or 0
        data['shopOrderMoneyAll'] = Decimal(shopOrderMoneyAll)
        # 商户结算总金额
        shopBalanceMoneyAll = _recordIncomes.filter(payway='shop_balance', scene='sendForExpense', changeWay='add').aggregate(sums=Sum('money'))['sums'] or 0
        data['shopBalanceMoneyAll'] = Decimal(shopBalanceMoneyAll)
        # 供应商结算总金额
        supplierBalanceMoneyAll = _itemOrder.filter(Q(scene='generay')|Q(scene='giftSection')).aggregate(sums=Sum('costPrice'))['sums'] or 0
        data['supplierBalanceMoneyAll'] = Decimal(supplierBalanceMoneyAll)
        # 总提现金额
        outMoneyAll = _recordIncomes.filter((Q(orderStatus='WAIT_SEND') | Q(orderStatus='FINISH')), payway='incomes', scene='outMoney').aggregate(sums=Sum('money'))['sums'] or 0
        data['outMoneyAll'] = Decimal(outMoneyAll)
        # 总提现手续费
        outMoneyServiceChargeAll = _recordIncomes.filter((Q(orderStatus='WAIT_SEND') | Q(orderStatus='FINISH')), payway='incomes', scene='outMoney').aggregate(sums=Sum('serviceCharge'))['sums'] or 0
        data['outMoneyServiceChargeAll'] = Decimal(outMoneyServiceChargeAll)
        # 结余可提现金额
        balanceIncomes = _users.aggregate(sums=Sum('incomes'))['sums'] or 0
        data['balanceIncomes'] = Decimal(balanceIncomes)
        # 释放补贴
        freeIncomeAll = _recordIncomes.filter(Q(orderStatus='FINISH'), payway='incomes', scene='lockedFree').aggregate(sums=Sum('money'))['sums'] or 0
        data['freeIncomeAll'] = Decimal(freeIncomeAll)

        year = date.strftime('%Y')
        month = date.strftime('%m')
        day = date.strftime('%d')
        print('dateCycle', dateCycle, year, month, day)
        _itemOrderReturn = None
        if dateCycle == 'day':
            data['dateValue'] = datetime.datetime.strptime(year + '-' + month + '-' + day, "%Y-%m-%d")
            _itemOrderReturn = _itemOrder.filter(orderStatus='HAS_RETURN',retunMoneyTime__year=year, retunMoneyTime__month=month, retunMoneyTime__day=day)
            _itemOrder = _itemOrder.filter(payTime__year=year, payTime__month=month, payTime__day=day)
            _recordIncomes = _recordIncomes.filter(createTime__year=year, createTime__month=month, createTime__day=day)
        elif dateCycle == 'month':
            data['dateValue'] = datetime.datetime.strptime(year + '-' + month, "%Y-%m")
            _itemOrderReturn = _itemOrder.filter(orderStatus='HAS_RETURN', retunMoneyTime__year=year, retunMoneyTime__month=month)
            _itemOrder = _itemOrder.filter(payTime__year=year, payTime__month=month)
            _recordIncomes = _recordIncomes.filter(createTime__year=year, createTime__month=month)
        elif dateCycle == 'year':
            data['dateValue'] = datetime.datetime.strptime(year, "%Y")
            _itemOrderReturn = _itemOrder.filter(orderStatus='HAS_RETURN', retunMoneyTime__year=year)
            _itemOrder = _itemOrder.filter(payTime__year=year)
            _recordIncomes = _recordIncomes.filter(createTime__year=year)
        # print('data', data)
        # 新增管理员
        addIncomeFromAdminNew = _recordIncomes.filter(payway='incomes', scene='addIncomeFromAdmin').aggregate(sums=Sum('money'))['sums'] or 0
        data['addIncomeFromAdminNew'] = Decimal(addIncomeFromAdminNew)
        # 新增管理员扣除
        subIncomeFromAdminNew = _recordIncomes.filter(payway='incomes', scene='subIncomeFromAdmin').aggregate(sums=Sum('money'))['sums'] or 0
        data['subIncomeFromAdminNew'] = Decimal(subIncomeFromAdminNew)
        # 新增管理员原积分
        addIncomesOriginalAdminNew = _recordIncomes.filter(payway='incomesOriginal', scene='addIncomeFromAdmin').aggregate(sums=Sum('money'))['sums'] or 0
        data['addIncomesOriginalAdminNew'] = Decimal(addIncomesOriginalAdminNew)
        # 新增管理员扣除原积分
        subIncomesOriginalFromAdminNew = _recordIncomes.filter(payway='incomesOriginal', scene='subIncomeFromAdmin').aggregate(sums=Sum('money'))['sums'] or 0
        data['subIncomesOriginalFromAdminNew'] = Decimal(subIncomesOriginalFromAdminNew)
        # 微信支付
        realPayForWxPay = _itemOrder.filter(payway='wxpay').aggregate(sums=Sum('realPay'))['sums'] or 0
        data['realPayForWxPay'] = Decimal(realPayForWxPay)
        # 微信支付退款
        realPayForWxPayReturn = _itemOrderReturn.filter(payway='wxpay').aggregate(sums=Sum('realPay'))['sums'] or 0
        data['realPayForWxPayReturn'] = Decimal(realPayForWxPayReturn)
        # 积分支付
        realPayForIncomes = _itemOrder.filter(payway='incomes').aggregate(sums=Sum('realPay'))['sums'] or 0
        data['realPayForIncomes'] = Decimal(realPayForIncomes)
        # 积分支付退款
        realPayForIncomesReturn = _itemOrderReturn.filter(payway='incomes').aggregate(sums=Sum('realPay'))['sums'] or 0
        data['realPayForIncomesReturn'] = Decimal(realPayForIncomesReturn)
        if dateCycle == 'day_bak':
            # 商户订单金额
            shopOrderMoney = _itemOrder.filter(scene='payForFranchisee').aggregate(sums=Sum('sellingPrice'))['sums'] or 0
            data['shopOrderMoney'] = Decimal(shopOrderMoney)
            # 商户结算金额
            shopBalanceMoney = _recordIncomes.filter(payway='shop_balance', scene='sendForExpense', changeWay='add').aggregate(sums=Sum('money'))['sums'] or 0
            data['shopBalanceMoney'] = Decimal(shopBalanceMoney)
            _shops = ShopDao().findAll()
            for shop in _shops:
                money = _recordIncomes.filter(shop=shop, payway='shop_balance', scene='sendForExpense', changeWay='add').aggregate(sums=Sum('money'))['sums'] or 0
                moneyLocked = _itemOrder.filter(shop=shop, scene='payForFranchisee').aggregate(sums=Sum('sellingPrice'))['sums'] or 0
                if money > 0:

                    receiptAccount = json.dumps({"types":'bank',"paywayCodeUrl":'',"creditedName": shop.creditedName, "creditedBank": shop.creditedBank, "creditedAccount": shop.creditedAccount, "bankCode": shop.bankCode})
                    data1 = {}
                    data1['scene'] = 'outMoney'
                    data1['shop'] = shop.id
                    data1['receiptAccount'] = receiptAccount
                    data1['fromUser'] = ''
                    data1['orderId'] = getFormatTime('%Y%m%d%H%M%S') + random_num(8)
                    data1['money'] = Decimal(money)
                    data1['moneyLocked'] = Decimal(moneyLocked) # moneyLocked字段强行当做订单金额使用
                    data1['serviceCharge'] = 0
                    data1['realMoney'] = money
                    data1['payway'] = 'incomes'
                    data1['changeWay'] = 'sub'
                    data1['orderStatus'] = 'WAIT_SEND'
                    RecordIncomesDao().create(data1)
            # 供应商结算金额
            print('供应商结算')
            supplierBalanceMoney = _itemOrder.filter(Q(scene='generay')|Q(scene='giftSection')).exclude(Q(content__contains='"item":1179') | Q(content__contains='"item": 1179')).aggregate(sums=Sum('costPrice'))['sums'] or 0
            data['supplierBalanceMoney'] = Decimal(supplierBalanceMoney)
            money = Decimal(supplierBalanceMoney)
            moneyLocked = _itemOrder.filter(Q(scene='generay')|Q(scene='giftSection')).exclude(Q(content__contains='"item":1179') | Q(content__contains='"item": 1179')).aggregate(sums=Sum('realPay'))['sums'] or 0
            if money>0:
                shop = ShopDao().findOneByObjId(32) or ShopDao().findAll().first()
                if shop:
                    shop = shop
                    receiptAccount = json.dumps({"types":'bank',"paywayCodeUrl":'',"creditedName": shop.creditedName, "creditedBank": shop.creditedBank, "creditedAccount": shop.creditedAccount, "bankCode": shop.bankCode})
                    data1 = {}
                    data1['scene'] = 'outMoney'
                    data1['shop'] = shop.id
                    data1['receiptAccount'] = receiptAccount
                    data1['fromUser'] = ''
                    data1['orderId'] = getFormatTime('%Y%m%d%H%M%S') + random_num(8)
                    data1['money'] = Decimal(money)
                    data1['moneyLocked'] = Decimal(moneyLocked)
                    data1['serviceCharge'] = 0
                    data1['realMoney'] = money
                    data1['payway'] = 'incomes'
                    data1['changeWay'] = 'sub'
                    data1['orderStatus'] = 'WAIT_SEND'
                    RecordIncomesDao().create(data1)

        # 新增用户提现
        newOutMoney = _recordIncomes.filter((Q(orderStatus='WAIT_SEND')|Q(orderStatus='FINISH')), payway='incomes', scene='outMoney').aggregate(sums=Sum('money'))['sums'] or 0
        data['newOutMoney'] = Decimal(newOutMoney)
        newOutServiceCharge = _recordIncomes.filter((Q(orderStatus='WAIT_SEND')|Q(orderStatus='FINISH')), payway='incomes', scene='outMoney', ).aggregate(sums=Sum('serviceCharge'))['sums'] or 0
        data['newOutServiceCharge'] = Decimal(newOutServiceCharge)

        # 释放补贴
        newFreeIncome = _recordIncomes.filter(Q(orderStatus='FINISH'), payway='incomes',  scene='lockedFree').aggregate(sums=Sum('money'))['sums'] or 0
        data['newFreeIncome'] = Decimal(newFreeIncome)

        print('data', data)
        FinanceForLesseeDao().create(data)

def startFinance():
    financeFun('day', datetime.datetime.now())
    financeFun('month', datetime.datetime.now())
    financeFun('year', datetime.datetime.now())

def startFinanceHistory():
    date_list = []
    begin_date = '2025-04-12'
    begin_date = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
    end_date = '2025-04-13'
    end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")

    while begin_date <= end_date:
        # date_str = begin_date.strftime("%Y-%m-%d")
        date_list.append(begin_date)
        begin_date += datetime.timedelta(days=1)

    print('date_list', date_list)
    for day in date_list:
        financeFun('day', day)
        # financeFun('month', datetime.datetime.now())
        # financeFun('year', datetime.datetime.now())
    # for month in range(1):
    #     month = '2024-' + str(month+5)
    #     month = datetime.datetime.strptime(str(month), "%Y-%m")
    #     print('month', month)
    #     financeFun('month', month)